import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pornhub_app/components/base_page/base_loading_widget.dart';
import 'package:pornhub_app/components/grid_view/heighted_grid_view.dart';
import 'package:pornhub_app/components/short_widget/video_base_cell.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/video_base_model.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/events.dart';
import 'package:pornhub_app/utils/extension.dart';

class ArroundFansPage extends StatefulWidget {
  final int userId;
  final VideoLayout videoLayout;
  const ArroundFansPage(
      {super.key, required this.userId, required this.videoLayout});

  @override
  State<ArroundFansPage> createState() => _ArroundFansPageState();
}

class _ArroundFansPageState extends State<ArroundFansPage> {
  late int _page = 1;
  final _pageSize = 20;

  var videos = <VideoBaseModel>[];
  var shouldShowDialog = false;
  StreamSubscription? subscription;
  StreamSubscription? layoutEvent;
  late VideoLayout layout;
  @override
  void initState() {
    layout = widget.videoLayout;
    _initListData();
    subscription = eventBus.on<BloggerRefreshEvent>().listen((event) async {
      if (event.tabName == "粉丝团专属") {
        _page = 1;
        await _initListData();
      }
    });
    layoutEvent = eventBus.on<VideoLayoutEvent>().listen((event) {
      layout = event.layout;
      if (mounted) setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      onLoad: () {
        _page++;
        return _initListData();
      },
      onRefresh: () {
        _page = 1;
        return _initListData();
      },
      child: shouldShowDialog != true
          ? CustomScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              slivers: [
                HeightedGridView.sliver(
                    crossAxisCount: layout == VideoLayout.small ? 2 : 1,
                    itemCount: videos.length,
                    itemBuilder: (ctx, i) => layout == VideoLayout.small
                        ? VideoBaseCell.small(video: videos[i])
                        : VideoBaseCell.big(video: videos[i]),
                    noData: videos.isEmpty,
                    columnSpacing: layout == VideoLayout.small ? 7.4.w : null,
                    rowSepratorBuilder: (ctx, i) => 10
                        .verticalSpaceFromWidth).sliverPaddingHorizontal(14.w),
              ],
            )
          : const BaseLoadingWidget(),
    );
  }

  Future _initListData() async {
    shouldShowDialog = true;
    final resp = await httpInstance.get<VideoBaseModel>(
        url: 'video/getByFansGroup',
        queryMap: {
          'userId': widget.userId,
          'page': _page,
          'pageSize': _pageSize,
        },
        complete: VideoBaseModel.fromJson);
    if (resp == null) {
      setState(() {
        shouldShowDialog = false;
      });
      return IndicatorResult.fail;
    } else {
      setState(() {
        if (_page == 1) {
          videos = resp;
        } else {
          videos.addAll(resp);
        }
        shouldShowDialog = false;
      });
      return IndicatorResult.success;
    }
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }
}
